package controllers

import (
	"github.com/jinzhu/gorm"
	"gopkg.in/kataras/iris.v6"
	"strconv"
	"layim/models"
	"strings"
	"encoding/base64"
	"io/ioutil"
	"os"
	"github.com/kataras/go-serializer"
	"layim/storage"
	"layim/helper"
	"github.com/kataras/go-serializer/json"
)

type DesktopController struct {
	Orm *gorm.DB
}

//桌面首页
func (h *DesktopController) Index(this *iris.Context) {
	_uid, err := helper.GetLoginId(this)
	param := map[string]interface{}{}
	if err != nil {
		param["userid"] = 0
		param["mygroup"] = "[]"
	} else {
		groups := h.getUserGroupsById(_uid)
		mygroups := []map[string]interface{}{}
		for _, v := range groups {
			mygroups = append(mygroups, map[string]interface{}{
				"text": v.Name,
				"name": "moveToGroup-" + strconv.Itoa(int(v.Id)),
			})
		}
		param["userid"] = _uid
		param["mygroup"], _ = serializer.SerializeToString(json.ContentType, mygroups)
	}
	flash := this.Session().GetFlash(FLASH_VERIFY_EMAIL)
	if flash == nil {
		param["flash"] = "{}"
	} else {
		param["flash"], _ = serializer.SerializeToString(json.ContentType, flash.(FlashSession))
	}
	this.Render("desktop.html", param)
}

//近七日代表事项
func (h *DesktopController) Calendar(this *iris.Context) {
	this.Write([]byte(`[]`))
}

//技术支持页面
func (h *DesktopController) TechnicalSupport(this *iris.Context) {
	this.Render("support.html", map[string]interface{}{"message": "Iris Go Technical Support!"})
}

//通过用户ID获取用户所有的分组记录
func (h *DesktopController) getUserGroupsById(userid int64) []models.Group {
	_groups := []models.Group{}
	h.Orm.Find(&_groups, &models.Group{UserId: userid}) //查询所有该用户下的分组
	groups := []models.Group{}                          //添加默认分组<<我的朋友>>
	groups = append(groups, models.Group{Id: 0, Name: "我的朋友", UserId: userid})
	groups = append(groups, _groups...)
	return groups
}

//裁剪图片处理
func (h *DesktopController) CropBox(this *iris.Context) {
	if this.IsAjax() {
		oldImage := this.FormValue("old")
		imgCode := strings.Replace(this.FormValue("imgcode"), "data:image/png;base64,", "", 1)
		if imgCode == "" || oldImage == "" {
			this.JSON(iris.StatusOK, responseJSON{Message: "图片内容不能为空", Errcode: 1})
			return
		}
		dataSource, err := base64.StdEncoding.DecodeString(imgCode) //todo 将前端图片的base64数据解析为文件元数据
		if err != nil {
			this.JSON(iris.StatusOK, responseJSON{Message: err.Error(), Errcode: 1})
			return
		}
		saveImg := "upload/" + helper.NowDate("Y-m-d") + "-" + helper.GetRandomStr(10, helper.RANDOM_ONLYINT) + ".jpg"
		err = ioutil.WriteFile(saveImg, dataSource, os.ModePerm)
		if err != nil {
			this.JSON(iris.StatusOK, responseJSON{Message: err.Error(), Errcode: 1})
			return
		}
		if strings.Index(oldImage, "upload/") == 0 {
			os.Remove(oldImage)
		}
		path, err := (&storage.Nos{}).UploadFile(saveImg)
		if err != nil {
			this.JSON(iris.StatusOK, responseJSON{Message: "保存图片成功", Data: "/" + saveImg, Errcode: 0})
			return
		} else {
			os.Remove(saveImg)
			this.JSON(iris.StatusOK, responseJSON{Message: "保存图片成功", Data: path, Errcode: 0})
			return
		}
	}
	path, err := (&storage.Nos{}).DownloadFile(this.URLParam("imgurl"))
	if err != nil {
		this.JSON(iris.StatusOK, responseJSON{Message: "打开图片失败:" + err.Error(), Errcode: 1})
		return
	}
	this.Render("cropbox.html", map[string]interface{}{"imgurl": path})
}

func (h *DesktopController) Theme(this *iris.Context) {
	this.Render("theme.html", nil)
}

func (h *DesktopController) Setting(this *iris.Context) {

}

func (h *DesktopController) VerifyMail(this *iris.Context) {
	_token := this.URLParam("token")
	if _token == "" {
		this.Session().SetFlash(FLASH_VERIFY_EMAIL, FlashSession{Result: false, Message: "缺少token信息"})
		this.Redirect("/")
		return
	}
	user := &models.User{}
	if h.Orm.First(user, &models.User{Token: _token}).RecordNotFound() {
		this.Session().SetFlash(FLASH_VERIFY_EMAIL, FlashSession{Result: false, Message: "没有找到对应的用户信息"})
		this.Redirect("/")
		return
	}
	user.Token = ""
	if h.Orm.Save(user).RowsAffected > 0 {
		this.Session().SetFlash(FLASH_VERIFY_EMAIL, FlashSession{Result: true, Message: "验证注册邮箱成功"})
		this.Redirect("/")
		return
	} else {
		this.Session().SetFlash(FLASH_VERIFY_EMAIL, FlashSession{Result: false, Message: "验证注册邮箱失败"})
		this.Redirect("/")
		return
	}
}

func (h *DesktopController) SendMail(this *iris.Context) {
	sendType := this.URLParam("type")
	email := this.URLParam("email")
	if !this.IsAjax() {
		this.JSON(iris.StatusOK, responseJSON{Errcode: 1, Message: "PAGE ERROR"})
		return
	}
	if sendType == "" || email == "" {
		this.JSON(iris.StatusOK, responseJSON{Errcode: 1, Message: "邮件发送参数错误"})
		return
	}
	if !helper.VerifyEmail(email) {
		this.JSON(iris.StatusOK, responseJSON{Errcode: 1, Message: "邮件地址错误"})
		return
	}
	switch sendType {
	case "register":
		url, err := base64.URLEncoding.DecodeString(this.URLParam("url"))
		if err != nil {
			this.JSON(iris.StatusOK, responseJSON{Errcode: 1, Message: "解析邮件地址错误,请重试:" + err.Error()})
			return
		}
		if err := helper.SendEmail("注册账号激活", string(url), []string{email}, this); err != nil {
			this.JSON(iris.StatusOK, responseJSON{Errcode: 1, Message: "发送邮件失败:" + err.Error()})
			return
		}
		this.JSON(iris.StatusOK, responseJSON{Errcode: 0, Message: "发送邮件成功"})
		return
	}
}
